<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
<!--      <el-form-item label="商店id" prop="storeId">-->
<!--        <el-input-->
<!--          v-model="queryParams.storeId"-->
<!--          placeholder="请输入商店id"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="商品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品类别" prop="categoryId">
          <el-cascader
            placeholder="请选择商品类别"
            v-model="categorySelects"
            :options="categoryOptions"
            :props="{ checkStrictly: true }"
            filterable
          ></el-cascader>
      </el-form-item>
      <el-form-item label="商品成本" prop="cost">
        <el-input
          v-model="queryParams.cost"
          placeholder="请输入商品成本"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="商品原价格" prop="priceSrc">-->
<!--        <el-input-->
<!--          v-model="queryParams.priceSrc"-->
<!--          placeholder="请输入商品原价格"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="商品实际价格" prop="price">-->
<!--        <el-input-->
<!--          v-model="queryParams.price"-->
<!--          placeholder="请输入商品实际价格"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="推荐指数" prop="recValue">
        <el-input
          v-model="queryParams.recValue"
          placeholder="请输入推荐指数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="查看次数" prop="viewNum">-->
<!--        <el-input-->
<!--          v-model="queryParams.viewNum"-->
<!--          placeholder="请输入查看次数"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="销量" prop="saleNum">-->
<!--        <el-input-->
<!--          v-model="queryParams.saleNum"-->
<!--          placeholder="请输入销量"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.shop_goods_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['shop:goods:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['shop:goods:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-arrow-up"
          size="mini"
          :disabled="multiple"
          @click="statusChangeHandle('','1')"
          v-hasPermi="['shop:goods:edit']"
        >上架</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-arrow-down"
          size="mini"
          :disabled="multiple"
          @click="statusChangeHandle('','0')"
          v-hasPermi="['shop:goods:edit']"
        >下架</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['shop:goods:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5" v-if="storeEnable">
        <el-button
          type="warning"
          plain
          icon="el-icon-close"
          size="mini"
          @click="handleClose"
        >关闭</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['shop:goods:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品图片" align="center" prop="imgAbbrev" width="100">
        <template v-slot="scope">
          <image-preview :src="scope.row.imgAbbrev" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="center" prop="name" />
      <el-table-column label="价格（元）" align="center" prop="price" >
        <template v-slot="scope">
          <span>{{(scope.row.price / 100).toFixed(2)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="推荐指数" align="center" prop="recValue" />
      <el-table-column label="查看次数" align="center" prop="viewNum" />
      <el-table-column label="销量" align="center" prop="saleNum" />
      <el-table-column label="总库存" align="center" prop="stockTotal" />
      <el-table-column label="状态" align="center" prop="status">
        <template v-slot="scope">
          <dict-tag :options="dict.type.shop_goods_status" :value="scope.row.status"/>
          <el-switch
            style="display: block"
            v-model="scope.row.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-value="1"
            inactive-value="0"
            @change="statusChange(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="上下架时间" align="center" prop="onOffTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.onOffTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['shop:goods:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleSpec(scope.row)"
            v-hasPermi="['shop:goods:edit']"
          >设置规格</el-button>
          <el-button
            v-show="scope.row.status === '0'"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['shop:goods:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改文创商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="商店" prop="storeId">
<!--              <treeselect v-model="form.storeId" :options="storeOptions" :normalizer="normalizer" placeholder="请选择商店" />-->
              <el-select
                v-model="form.storeId"
                filterable
                remote
                reserve-keyword
                placeholder="请输入关键词"
                :remote-method="getStoreList"
                :loading="loading">
                <el-option
                  v-for="item in storeOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品类别" prop="categoryId">
              <treeselect v-model="form.categoryId" :options="categoryEditOptions" :normalizer="normalizer" placeholder="请选择商品类别" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品缩略图" prop="imgAbbrev">
              <image-upload v-model="form.imgAbbrev" :biz-id="form.id" biz-code="SHOP_GOODS_ABBREV" :limit="1"></image-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品轮播图" prop="imgDetail">
              <image-upload v-model="form.imgDetail" :biz-id="form.id" biz-code="SHOP_GOODS_DETAIL" zoom="0"></image-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品描述" prop="goodsDesc">
<!--              <el-input v-model="form.goodsDesc" type="textarea" placeholder="请输入内容" />-->
              <editor v-model="form.goodsDesc" :min-height="192"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品成本" prop="cost">
              <el-input-number v-model="form.cost" placeholder="请输入商品成本" controls-position="right" :min="0" :step="100"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品原价格" prop="priceSrc">
              <el-input-number v-model="form.priceSrc" placeholder="请输入商品原价格" controls-position="right" :min="0" :step="100"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品实际价格" prop="price">
              <el-input-number v-model="form.price" placeholder="请输入商品实际价格" controls-position="right" :min="0" :step="100"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="推荐指数" prop="recValue">
              <el-input v-model="form.recValue" placeholder="请输入推荐指数" maxlength="4"/>
            </el-form-item>
          </el-col>
<!--          <el-col :span="12">-->
<!--            <el-form-item label="查看次数" prop="viewNum">-->
<!--              <el-input v-model="form.viewNum" placeholder="请输入查看次数" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="销量" prop="saleNum">-->
<!--              <el-input v-model="form.saleNum" placeholder="请输入销量" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.shop_goods_status"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
<!--        <el-form-item label="上下架时间" prop="onOffTime">-->
<!--          <el-date-picker clearable-->
<!--            v-model="form.onOffTime"-->
<!--            type="date"-->
<!--            value-format="yyyy-MM-dd"-->
<!--            placeholder="请选择上下架时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listGoods, getGoods, delGoods, addGoods, updateGoods, onOffGoods } from "@/api/shop/goods";
import { listCategory, handleCascader } from "@/api/shop/category";
import { listStore, getStore } from "@/api/shop/store";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Goods",
  dicts: ['shop_goods_status'],
  components: {
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 商店id
      storeId: '',
      // 选中数组
      ids: [],
      // 选中名称数组
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文创商品表格数据
      goodsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        storeId: null,
        categoryId: null,
        name: null,
        cost: null,
        priceSrc: null,
        price: null,
        recValue: null,
        viewNum: null,
        saleNum: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        storeId: [
          { required: true, trigger: "blur", message: "请选择商店" }
        ],
      },
      // 商品类别下拉查询
      categoryOptions: [],
      // 编辑时商品类别选择框
      categoryEditOptions: [],
      // 商品类别选中项
      categorySelects: [],
      // 商店数据源
      storeOptions: [],
      // 商店选择遮罩
      storeLoading: false
    };
  },
  created() {
    const storeId = this.$route.query && this.$route.query.storeId;
    if (storeId) {
      this.storeId = storeId;
      this.queryParams.storeId = storeId;
    }
    this.getList();
    this.getTreeselect();
  },
  activated() {
    this.getList();
  },
  computed: {
    // 是否禁用
    storeEnable() {
      return this.storeId;
    },
  },
  methods: {
    /** 转换文创商品类别数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    /** 查询文创商品类别下拉树结构 */
    getTreeselect() {
      listCategory().then(response => {
        this.categoryOptions = [];
        const editData = { id: 0, name: '顶级节点', children: [] };
        editData.children = this.handleTree(response.data, "id", "parentId");
        this.categoryEditOptions.push(editData);
        this.categoryOptions = handleCascader(response.data);
      });
    },
    /** 查询文创商店列表 */
    getStoreList(query) {
      if (query !== '') {
        this.storeLoading = true;
        const queryParams = {
          name: query
        }
        listStore(queryParams).then(response => {
          this.storeOptions = response.rows;
          this.storeLoading = false;
        });
      }
    },
    /** 查询文创商品列表 */
    getList() {
      this.loading = true;
      listGoods(this.queryParams).then(response => {
        this.goodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        storeId: null,
        categoryId: null,
        name: null,
        imgAbbrev: null,
        goodsDesc: null,
        cost: null,
        priceSrc: null,
        price: null,
        recValue: null,
        viewNum: null,
        saleNum: null,
        status: "1",
        onOffTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
      this.categorySelects = []
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.names = selection.map(item => item.name)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      // this.reset();
      // this.open = true;
      // this.title = "添加文创商品";
      this.$tab.openPage("添加商品", '/shop/goods-add/index', {storeId: this.storeId});
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const id = row.id || this.ids
      const name = row.name || this.names
      this.$tab.openPage("修改[" + name + "]商品", '/shop/goods-add/index',{storeId: this.storeId, goodsId: id});
      // this.reset();
      // const id = row.id || this.ids
      // this.storeOptions = []
      // getGoods(id).then(response => {
      //   this.form = response.data;
      //   this.open = true;
      //   this.title = "修改文创商品";
      //   getStore(response.data.storeId).then(response => {
      //     this.storeOptions.push(response.data);
      //   })
      // });
    },
    /** 上架/下架按钮操作 */
    statusChange(row) {
      this.statusChangeHandle(Array.of(row.id), row.status)
    },
    /** 上架/下架操作 */
    statusChangeHandle(id, status) {
      const ids = id || this.ids
      const data = {
        ids: ids,
        status: status
      }
      onOffGoods(data).then(response => {
        this.$modal.msgSuccess(response.msg);
        this.getList();
      }).catch(() => {});
    },
    /** 设置商品规格按钮操作 */
    handleSpec(row) {
      const id = row.id;
      const name = row.name;
      this.$tab.openPage("[" + name + "]配置规格", '/shop/goods-spec-edit/index/' + id);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateGoods(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGoods(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const names = row.name || this.names;
      this.$modal.confirm('是否确认删除商品名称为"' + names + '"的数据项？').then(function() {
        return delGoods(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('shop/goods/export', {
        ...this.queryParams
      }, `goods_${new Date().getTime()}.xlsx`)
    },
    // 返回按钮
    handleClose() {
      const obj = { path: "/shop/goods/store" };
      this.$tab.closeOpenPage(obj);
    },
  },
  watch: {
    categorySelects(val) {
      this.queryParams.categoryId = val[val.length - 1];
    }
  }
};
</script>
